package com.example.sentinel.common.config;

import cn.hutool.json.JSONUtil;
import com.example.sentinel.common.bean.ErrorException;
import com.example.sentinel.common.bean.FailException;
import com.example.sentinel.common.bean.Result;
import com.example.sentinel.common.bean.ResultCode;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * 自定义feign错误信息
 *
 * @author luojm
 * 2019-11-22 15:24:58
 */
@Slf4j
@Configuration
public class FeignErrorDecoder implements ErrorDecoder {
    @Override
    public Exception decode(String methodKey, Response response) {
        Exception exception = null;
        try {
            String json = Util.toString(response.body().asReader());
            exception = new RuntimeException(json);
            Result result = JSONUtil.toBean(json, Result.class);
            if (ResultCode.FAIL.getCode().equals(result.getCode())) {
                exception = new FailException(result.getMsg(),null,true,false);
            }else if (ResultCode.PARAMERROR.getCode().equals(result.getCode())) {
                exception = new IllegalArgumentException(result.getMsg());
            }else {
                exception = new ErrorException(result.getMsg(),null,true,false);
            }
        } catch (IOException ex) {
            log.error(ex.getMessage(), ex);
        }
        return exception;
    }
}
